const dataPool: Array<number> = []


export function clientMessageHandle(params: {
  host: string;
  port: number;
}, message: Array<number>) {
  dataPool.push(...message)
  parsePacket(params)
}

function parsePacket(params: {
  host: string;
  port: number;
}) {
  // 从 dataPool 截取 A5 开头的
  const startIndex = dataPool.findIndex(data => data === 0xA5);
  if (startIndex === -1) {
    return;
  }
  const len = dataPool[startIndex + 1];
  const endIndex = startIndex + len + 1;
  // 根据长度截取数据,截取到后进行处理
  const packetData = dataPool.splice(startIndex, endIndex);

  if (packetData.length < 14) return

  // 计算校验和
  let calculatedCK = calculateCK(packetData.slice(0, -1));
  let receivedCK = packetData[packetData.length - 1];

  // 检查校验和是否匹配
  if (calculatedCK !== receivedCK) {
    // console.error('校验和错误');
    return;
  }


  const antennaNumber = packetData[7];
  if (antennaNumber === 0) return

  // 提取数据部分（如果有）
  const epc_data = packetData.slice(10, -5);

  function byteArrayToHexString(bytes) {
    const str = bytes.map(byte => byte.toString(16).padStart(2, '0')).join(' ');
    // 去除空格并大写
    return str.replace(/\s+/g, '').toUpperCase();
  }

  const rfid = byteArrayToHexString(epc_data);

  if (!rfid) return

  console.log('rfid', rfid);

  const key = `${params.host}-${antennaNumber}`;
  const sendResult = {
    key,
    ip: params.host,
    port: params.port,
    antenna: antennaNumber,
    rfid: rfid,
  };


  on_set_rfid_judgment(sendResult)

  if (dataPool.length >= startIndex + 25) {
    console.log('再次执行')
    parsePacket(params)
  }

}


function calculateCK(buffer: Array<number>) {
  let sum = 0;
  for (let i = 0; i < buffer.length; i++) {
    sum += buffer[i];
  }
  return (~sum + 1) & 0xFF;
}
